var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const joi = require('joi')
// 导入路由模块
const userRouter = require('./routes/users');
const userinfoRouter = require('./routes/userinfo')
const getUserRouter = require('./routes/getUser')
const releaseRouter = require('./routes/article')
const chatRouter = require('./routes/chat')

var app = express();
// 改写入口
var http = require('http');
var server = http.createServer(app);

var url = require('url')



const WebSocket = require('ws');

//创建服务 port是端口
const wss = new WebSocket.Server({ port: 3030 });

//引入socket服务器
var websocketServer = require("./bin/websocketServer")

// 启动socket服务
websocketServer(wss)


app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// 错误处理中间件
app.use((req, res, next) => {
  // status 默认值为1，表示失败的情况
  // err的值，可能是一个错误的对象，也可能是一个错误的描述字符串
  res.cc = function (err, status = 1) {
    res.send({
      status,
      message: err instanceof Error ? err.message : err
    })
  }
  next()
})
// 在路由之前解析token的中间件
const expressJWT = require('express-jwt')
const config = require('./config');

app.use(expressJWT({ secret: config.jwtSecreKey }).unless({ path: [/^\/api\/user/] }))

// 路由
// 登录注册
app.use('/api/user', userRouter);
// 账号信息
app.use('/api/my', userinfoRouter);
// 获取医生和分类列表
app.use('/api/getuser', getUserRouter);
// 医疗常识
app.use('/api/article', releaseRouter)
// 拿到聊天对象
app.use('/api/chat', chatRouter)



// 定义错误级别中间件
app.use((err, req, res, next) => {
  // 验证失败导致的错误
  if (err instanceof joi.ValidationError) return res.cc('请按照规定填写表单!')
  // 身份认证失败后的错误
  if (err.name = 'UnauthorizedError') return res.cc('身份认证失败！')
  // 未知的错误
  res.cc(err)
})


server.listen('3000');
